const express = require("express");
const { createServer } = require("node:http");
const { join } = require("node:path");
const app = express();
const server = createServer(app);
const { Server } = require("socket.io"); //socket.io
var router = express.Router();
var multiparty = require('multiparty');
var { userModel, listModel, cateModel, loginModel, shopModel, dingModel, role,
    ordermanagement, stag, pcuser, menu, users, users1 } = require('../model/model.js');
const cors = require('cors');
const path = require('path')
app.use(cors());
app.use('/uploads', express.static(path.join(__dirname, '/uploads')));
app.use('/audioUploads', express.static(path.join(__dirname, 'audioUploads')));
// 引入 fs 模块
const fs = require('fs')
const multer = require('multer');

const io = new Server(server, { cors: true }, { connectionStateRecovery: {} });

var Svgcatcha = require("svg-captcha");
var jwt = require('jsonwebtoken');



const bodyParser = require("body-parser");
const fse = require("fs-extra");
const multipart = require("connect-multiparty");
const multipartMiddleware = multipart();
const UPLOADS_DIR = path.resolve("uploads");

// 验证码
router.get("/message", async (req, res) => {
    let options = {
        size: 4,
        noise: 4,
        color: true,
        background: "white",
        height: 35,
    };
    let { data, text } = Svgcatcha.create(options);
    res.send({ code: 200, data: data, text });
});

// 登录
router.post("/login", async (req, res) => {
    let { username, password } = req.body;
    let data = await pcuser.findOne({ username, password }).populate("role_id");
    if (data) {
        let token = jwt.sign({ username, password }, "ewrjifnheuwinuiwevbn", {
            expiresIn: 60 * 60 * 24,
        });
        res.send({
            code: 200,
            msg: "登录成功",
            token,
            data,
        });
    } else {
        res.send({
            code: 400,
            msg: "用户名或密码错误",
        });
    }
});

// user  用户
router.get("/user", async (req, res) => {
    let data = await pcuser.find();
    res.send({
        code: 200,
        data,
    });
});

router.post("/useradd", (req, res) => {
    pcuser.create(req.body);
    res.send({
        code: 200,
        msg: "添加成功",
    });
});

// 获取用户的权限
router.post("/getmenu", async (req, res) => {
    let { role_id } = req.body;

    let [{ menus }] = await role.find({ _id: role_id });

    let menuList = await menu.find().lean();

    // console.log(menuList);
    let menuArr = []
    menus.forEach(item => {
        menuList.forEach(item1 => {
            if (String(item) == String(item1._id)) {
                menuArr.push(item1)
            }
        })
    })
    // console.log(menuArr);
    let menuObj = {}
    menuArr.forEach(item => {
        menuObj[item._id] = item
    })
    // console.log(menuObj);
    let arr = []
    menuArr.forEach(item => {
        if (!item.parentId) {
            arr.push(item)
        } else {
            if (menuObj[item.parentId] && !menuObj[item.parentId].children) {
                menuObj[item.parentId].children = []
            }
            menuObj[item.parentId] && menuObj[item.parentId].children.push(item)
        }
    })
    console.log(arr);

    res.send({
        code: 200,
        msg: "获取成功",
        arr,
    });
});

// role  角色  1
router.get("/role", async (req, res) => {
    let data = await role.find();
    res.send({
        code: 200,
        data,
    });
});

router.post("/roleadd", (req, res) => {
    role.create(req.body);
    res.send({
        code: 200,
        msg: "添加成功",
    });
});

// menu  菜单
router.get("/menu", async (req, res) => {
    let data = await menu.find();
    res.send({
        code: 200,
        data,
    });
});

router.post("/menuadd", (req, res) => {
    console.log(req.body);

    menu.create(req.body);

    res.send({
        code: 200,
        msg: "添加成功",
    });
});



// 用户分析
router.post("/addusers", (req, res) => {
    users.create(req.body);
    res.send({
        code: 200,
        msg: "添加成功",
    });
});
router.get("/getusers", async (req, res) => {
    let { page, pagesize } = req.query
    let data = await users.find().skip((page - 1) * pagesize).limit(pagesize);
    let total = await users.find().countDocuments()
    res.send({
        code: 200,
        data,
        total
    });
});

// 交易分析
router.post("/addusers1", (req, res) => {
    users1.create(req.body);
    res.send({
        code: 200,
        msg: "添加成功",
    });
});
router.get("/getusers1", async (req, res) => {
    let { page, pagesize } = req.query
    let data = await users1.find().skip((page - 1) * pagesize).limit(pagesize);
    let total = await users1.find().countDocuments()
    res.send({
        code: 200,
        data,
        total
    });
});

// 获取分类中列表数据
router.get('/list', async (req, res) => {
    const { name } = req.query
    let queryArr = [{}]
    let regName = new RegExp(name)
    if (regName != '') {
        queryArr.push({ name: regName })
    }
    let list = await listModel.find({ $and: queryArr }).populate('cid')
    res.send({
        code: 200,
        msg: "获取成功",
        list
    })
})
// 添加分类中列表数据
router.post('/add', async (req, res) => {
    listModel.create(req.body)
    res.send({
        code: 200,
        msg: "添加成功"
    })
})
// 获取分类数据
router.get('/cate', async (req, res) => {
    let cate = await cateModel.find()
    res.send({
        code: 200,
        msg: "获取成功",
        cate
    })
})
// 添加分类数据
router.post('/addcate', async (req, res) => {
    cateModel.create(req.body)
    res.send({
        code: 200,
        msg: "添加成功"
    })
})
// 点击按钮，添加数量
router.put('/addnum/:_id', async (req, res) => {
    let _id = req.params._id
    await shopModel.updateOne({ _id: _id }, { $inc: { num: 1 } })
    res.send({
        code: 200,
        msg: "修改成功",
    })
})
// 点击按钮，减少数量
router.put('/subnum/:_id', async (req, res) => {
    let _id = req.params._id
    await shopModel.updateOne({ _id: _id }, { $inc: { num: -1 } })
    res.send({
        code: 200,
        msg: "修改成功",
    })
})
// 获取提货人信息
router.get('/login', async (req, res) => {
    let login = await loginModel.find()
    res.send({
        code: 200,
        msg: "获取成功",
        login
    })
})
// 添加提货人信息
router.post('/addlogin', async (req, res) => {
    loginModel.create(req.body)
    res.send({
        code: 200,
        msg: "添加成功"
    })
})
// 修改提货人数据
router.put('/updlogin', async (req, res) => {
    const { _id, loginname, loginpass } = req.body;
    try {
        await loginModel.updateOne({ _id: _id }, { loginname, loginpass });
        res.send({ code: 200, msg: '修改成功' });
    } catch (err) {
        res.status(500).send({ code: 500, msg: '更新数据失败' });
    }
});
// 获取购物车数据
router.get('/shop', async (req, res) => {
    let shop = await shopModel.find().populate('shopid')
    res.send({
        code: 200,
        msg: "获取成功",
        shop
    })
})
// 添加购物车数据1
router.post('/addshop', async (req, res) => {
    shopModel.create(req.body)
    res.send({
        code: 200,
        msg: "添加成功"
    })
})
// 修改购物车数据
router.put('/updshop', async (req, res) => {
    let body = req.body
    await shopModel.updateOne({ _id: body._id }, body)
    res.send({
        code: 200,
        msg: "修改成功"
    })
})
// 删除购物车数据
router.delete('/delshop/:_id', async (req, res) => {
    let { _id } = req.params
    console.log(_id);
    await shopModel.deleteOne({ _id })
    res.send({
        code: 200,
        msg: "删除成功"
    })
})
// 批量删除购物车信息
router.post("/delAllshop", async (req, res) => {
    let { ids } = req.body;
    await shopModel.deleteMany({ _id: ids });
    res.send({
        code: 200,
        msg: "删除成功",
    });
});
// 获取订单信息
router.get('/ding', async (req, res) => {
    let ding = await dingModel.find()
    res.send({
        code: 200,
        msg: "获取成功",
        ding
    })
})
// 添加订单信息
router.post('/addding', async (req, res) => {
    dingModel.create(req.body)
    res.send({
        code: 200,
        msg: "添加成功"
    })
})
// 获取详情
router.get('/xiang', async (req, res) => {
    let { _id } = req.query
    let xiang = await listModel.findOne({ _id })
    res.send({
        code: 200,
        xiang
    })
})
// 获取详情
router.get('/xiangs', async (req, res) => {
    let { _id } = req.query
    let xiangs = await shopModel.findOne({ _id })
    res.send({
        code: 200,
        xiangs
    })
})
//引入支付宝配置文件`
const alipaySdk = require('./alipayUtil');
const AlipayFormData = require('alipay-sdk/lib/form').default;
router.post('/api/payment', function (req, res) {
    console.log(req.body, 'aaaaaaaaaaaaa')
    //订单号
    let orderId = req.body.orderId;
    //商品总价
    let price = req.body.price;
    //购买商品的名称
    let name = req.body.name;
    // 开始对接支付宝API
    const formData = new AlipayFormData();
    //调用setMethod 并传入get,会返回可以跳转到支付页面的url,
    formData.setMethod("get");
    // 支付时信息
    const bizContent = {
        out_trade_no: orderId, //订单号
        product_code: "FAST_INSTANT_TRADE_PAY",
        total_amount: price, //总价格
        subject: name, //商品名称
        body: "商品详情", //商品描述
    };
    formData.addField("bizContent", bizContent);
    //支付成功或失败的返回链接（前端页面）
    formData.addField("returnUrl", "http://localhost:5173/shopstatus");
    // 返回promise
    const result = alipaySdk.exec(
        // "alipay.trade.page.pay",
        "alipay.trade.wap.pay",
        {},
        { formData: formData }
    ).catch(error => console.error('caught error!', error));
    //对接支付宝成功，支付宝返回的数据
    result.then((resp) => {
        res.send({
            data: {
                code: 200,
                success: true,
                msg: "支付中",
                result: resp,
            },
        });
    });
});
app.get("/", (req, res) => {
  res.send("<h1>Hello world</h1>");
});

app.get("/", (req, res) => {
  res.sendFile(join(__dirname, "index.html"));
});

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = join(__dirname, 'uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdir(uploadDir, { recursive: true }, (err) => {
        if (err) {
          return cb(err);
        }
        cb(null, uploadDir);
      });
    } else {
      cb(null, uploadDir);
    }
  },
  filename: (req, file, cb) => {
    const buf = Buffer.from(file.originalname, 'latin1');
    const fileName = buf.toString('utf-8');
    cb(null, Date.now() + '-' + fileName);
  },
});

const storageAudio = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = join(__dirname, 'audioUploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdir(uploadDir, { recursive: true }, (err) => {
        if (err) {
          return cb(err);
        }
        cb(null, uploadDir);
      });
    } else {
      cb(null, uploadDir);
    }
  },
  filename: (req, file, cb) => {
    // 尝试从blob对象获取格式信息或设置默认格式
    const fileName = Date.now() + '.wav';
    cb(null, fileName);
  },
});
const uploadAudio = multer({ storage: storageAudio });

app.post('/uploadAudio', uploadAudio.single('audio'), (req, res) => {
  const audioPath = req.file.path;
  // 从请求中获取用户信息
  const sender = req.body.username;
  io.emit('audioMessage', { path: audioPath, username: sender });
  res.send('音频上传成功');
});

const upload = multer({ storage });

app.post('/upload', upload.single('image'), (req, res) => {
  const imagePath = req.file.path;
  // 从请求中获取用户信息
  const sender = req.body.username;
  io.emit('imageMessage', { path: imagePath, isUploaded: true, username: sender });
  res.send('图片上传成功');
});

io.on('connection', (socket) => {
  socket.on('message', (dispatcher, user) => {
    console.log(dispatcher, user);
    io.emit('message', dispatcher, user);
  });

  socket.on('imageMessage', async (imageData, user) => {
    const base64Data = imageData.replace(/^data:image\/\w+;base64,/, '');
    const buffer = Buffer.from(base64Data, 'base64');
    const uploadDir = join(__dirname, 'uploads');
    try {
      await fs.access(uploadDir);
    } catch (error) {
      await fs.mkdir(uploadDir, { recursive: true });
    }
    const imageName = Date.now() + '-' + encodeURIComponent(imageData.match(/filename="([^"]+)"/)[1]);
    const imagePath = join(uploadDir, imageName);
    // const imagePath = join(uploadDir, `${Date.now()}.png`);
    try {
      await fs.writeFile(imagePath, buffer);
      io.emit('imageMessage', { path: imagePath, isUploaded: false });
    } catch (error) {
      console.error('保存图片时出现错误：', error);
    }
  });
  // socket.on('videoMessage', async (video, user) => {
  //   console.log(video, user);
  //   io.emit('videoMessage', video, user);
  // })
});

server.listen(3001, () => {
  console.log("server running at http://localhost:3001");
});
module.exports = router;
